

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';

interface LoginFormData {
  userAccount: string;
  userPassword: string;
}

interface FormErrors {
  userAccount: string;
  userPassword: string;
}

interface LoginStatus {
  type: 'success' | 'error' | null;
  message: string;
}

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 表单数据状态
  const [formData, setFormData] = useState<LoginFormData>({
    userAccount: '',
    userPassword: ''
  });

  // 表单错误状态
  const [formErrors, setFormErrors] = useState<FormErrors>({
    userAccount: '',
    userPassword: ''
  });

  // 登录状态
  const [loginStatus, setLoginStatus] = useState<LoginStatus>({
    type: null,
    message: ''
  });

  // 密码显示状态
  const [isPasswordVisible, setIsPasswordVisible] = useState(false);

  // 登录加载状态
  const [isLoginLoading, setIsLoginLoading] = useState(false);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '登录 - 精进坊';
    return () => {
      document.title = originalTitle;
    };
  }, []);

  // 验证函数
  const validateUserAccount = (value: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^1[3-9]\d{9}$/;
    const accountRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]{4,20}$/;
    return emailRegex.test(value) || phoneRegex.test(value) || accountRegex.test(value);
  };

  const validatePassword = (value: string): boolean => {
    return value.length >= 6;
  };

  // 显示错误信息
  const showError = (field: keyof FormErrors, message: string) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: message
    }));
  };

  // 隐藏错误信息
  const hideError = (field: keyof FormErrors) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: ''
    }));
  };

  // 显示登录状态
  const showLoginStatus = (type: 'success' | 'error', message: string) => {
    setLoginStatus({ type, message });
  };

  // 隐藏登录状态
  const hideLoginStatus = () => {
    setLoginStatus({ type: null, message: '' });
  };

  // 处理输入变化
  const handleInputChange = (field: keyof LoginFormData, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理输入框失去焦点
  const handleInputBlur = (field: keyof LoginFormData) => {
    const value = formData[field];
    
    if (field === 'userAccount' && value) {
      if (!validateUserAccount(value)) {
        showError(field, '请输入有效的用户账号、邮箱或手机号');
      } else {
        hideError(field);
      }
    }
    
    if (field === 'userPassword' && value) {
      if (!validatePassword(value)) {
        showError(field, '密码至少需要6位字符');
      } else {
        hideError(field);
      }
    }
  };

  // 切换密码显示
  const togglePasswordVisibility = () => {
    setIsPasswordVisible(!isPasswordVisible);
  };

  // 处理表单提交
  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 清除之前的错误信息
    setFormErrors({ userAccount: '', userPassword: '' });
    hideLoginStatus();
    
    // 获取表单数据
    const { userAccount, userPassword } = formData;
    
    // 验证表单
    let isValid = true;
    
    if (!userAccount.trim()) {
      showError('userAccount', '请输入用户账号、邮箱或手机号');
      isValid = false;
    } else if (!validateUserAccount(userAccount.trim())) {
      showError('userAccount', '请输入有效的用户账号、邮箱或手机号');
      isValid = false;
    }
    
    if (!userPassword) {
      showError('userPassword', '请输入密码');
      isValid = false;
    } else if (!validatePassword(userPassword)) {
      showError('userPassword', '密码至少需要6位字符');
      isValid = false;
    }
    
    if (!isValid) {
      return;
    }
    
    // 显示加载状态
    setIsLoginLoading(true);
    
    try {
      // 调用真实的后端API
      const response = await fetch('http://localhost:8121/api/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userAccount: userAccount.trim(),
          userPassword: userPassword
        }),
        credentials: 'include' // 包含cookies，用于session管理
      });
      
      const result = await response.json();
      
      if (response.ok && result.code === 0) {
        // 登录成功
        showLoginStatus('success', '登录成功！');
        
        // 保存用户信息到localStorage（可选）
        if (result.data) {
          localStorage.setItem('userInfo', JSON.stringify(result.data));
        }
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          navigate('/home');
        }, 1000);
      } else {
        // 登录失败
        showLoginStatus('error', result.message || '登录失败，请检查账号和密码');
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      showLoginStatus('error', '网络错误，请稍后重试');
    } finally {
      setIsLoginLoading(false);
    }
  };

  // 处理忘记密码
  const handleForgotPassword = (e: React.MouseEvent) => {
    e.preventDefault();
    showLoginStatus('error', '忘记密码功能正在开发中，请联系客服');
  };

  // 处理社交媒体登录
  const handleSocialLogin = (platform: 'wechat' | 'qq') => {
    const messages = {
      wechat: '微信登录功能正在开发中',
      qq: 'QQ登录功能正在开发中'
    };
    showLoginStatus('error', messages[platform]);
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent, nextField?: () => void) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (nextField) {
        nextField();
      } else {
        handleFormSubmit(e as any);
      }
    }
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
        <div className="flex items-center justify-center h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className={`w-10 h-10 ${styles.gradientBg} rounded-xl flex items-center justify-center`}>
              <i className="fas fa-graduation-cap text-white text-lg"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">精进坊</h1>
          </div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="pt-16 min-h-screen flex items-center justify-center p-6">
        <div className="w-full max-w-md">
          {/* 登录卡片 */}
          <div className={`${styles.loginCard} rounded-card shadow-card p-8`}>
            {/* 登录标题 */}
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-text-primary mb-2">欢迎回来</h2>
              <p className="text-text-secondary text-sm">登录您的账号，继续您的成长之旅</p>
            </div>

            {/* 登录表单 */}
            <form onSubmit={handleFormSubmit} className="space-y-6">
              {/* 用户账号输入框 */}
              <div className="space-y-2">
                <label htmlFor="user-account" className="block text-sm font-medium text-text-primary">
                  用户账号
                </label>
                <div className="relative">
                  <input
                    type="text"
                    id="user-account"
                    name="user-account"
                    value={formData.userAccount}
                    onChange={(e) => handleInputChange('userAccount', e.target.value)}
                    onBlur={() => handleInputBlur('userAccount')}
                    onKeyDown={(e) => handleKeyDown(e, () => document.getElementById('password')?.focus())}
                    className={`w-full px-4 py-3 pl-12 border border-gray-200 rounded-lg ${styles.formInputFocus} transition-all duration-200`}
                    placeholder="请输入用户账号、邮箱或手机号"
                    required
                  />
                  <i className="fas fa-user absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
                {formErrors.userAccount && (
                  <div className={styles.errorMessage}>{formErrors.userAccount}</div>
                )}
              </div>

              {/* 密码输入框 */}
              <div className="space-y-2">
                <label htmlFor="password" className="block text-sm font-medium text-text-primary">
                  密码
                </label>
                <div className="relative">
                  <input
                    type={isPasswordVisible ? 'text' : 'password'}
                    id="password"
                    name="password"
                    value={formData.userPassword}
                    onChange={(e) => handleInputChange('userPassword', e.target.value)}
                    onBlur={() => handleInputBlur('userPassword')}
                    onKeyDown={(e) => handleKeyDown(e)}
                    className={`w-full px-4 py-3 pl-12 pr-12 border border-gray-200 rounded-lg ${styles.formInputFocus} transition-all duration-200`}
                    placeholder="请输入密码"
                    required
                  />
                  <i className="fas fa-lock absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                  <button
                    type="button"
                    onClick={togglePasswordVisibility}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-text-primary"
                  >
                    <i className={`fas ${isPasswordVisible ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {formErrors.userPassword && (
                  <div className={styles.errorMessage}>{formErrors.userPassword}</div>
                )}
              </div>

              {/* 忘记密码链接 */}
              <div className="text-right">
                <a
                  href="#"
                  onClick={handleForgotPassword}
                  className="text-sm text-secondary hover:text-accent transition-colors"
                >
                  忘记密码？
                </a>
              </div>

              {/* 登录按钮 */}
              <button
                type="submit"
                disabled={isLoginLoading}
                className="w-full py-3 bg-secondary text-white rounded-lg font-medium hover:bg-accent transition-colors duration-200 flex items-center justify-center space-x-2"
              >
                <span>{isLoginLoading ? '登录中...' : '登录'}</span>
                {isLoginLoading && <i className="fas fa-spinner fa-spin"></i>}
              </button>

              {/* 登录状态提示 */}
              <div className="text-center">
                {loginStatus.type === 'success' && (
                  <div className={styles.successMessage}>{loginStatus.message}</div>
                )}
                {loginStatus.type === 'error' && (
                  <div className={styles.errorMessage}>{loginStatus.message}</div>
                )}
              </div>
            </form>

            {/* 注册链接 */}
            <div className="mt-8 text-center pt-6 border-t border-gray-100">
              <p className="text-text-secondary text-sm">
                还没有账号？
                <Link
                  to="/register"
                  className="text-secondary hover:text-accent font-medium transition-colors ml-1"
                >
                  立即注册
                </Link>
              </p>
            </div>
          </div>

          {/* 其他登录方式 */}
          <div className="mt-6 text-center">
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-gray-200"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-4 bg-gray-50 text-text-secondary">或使用以下方式登录</span>
              </div>
            </div>
            
            <div className="mt-4 flex justify-center space-x-4">
              <button
                onClick={() => handleSocialLogin('wechat')}
                className="w-10 h-10 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center justify-center"
              >
                <i className="fab fa-weixin"></i>
              </button>
              <button
                onClick={() => handleSocialLogin('qq')}
                className="w-10 h-10 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center"
              >
                <i className="fab fa-qq"></i>
              </button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};

export default LoginPage;

